package com.gitlab.lucky.common.utils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

public class HttpClientUtil {

    /**
     * 发送模板消息的方法
     * @param templateMsgUrl 模板消息请求URL
     * @param paramStr  模板消息json字符串
     * @return
     */
    public static String doTemplateMsgPost(String templateMsgUrl,String paramStr){
        String res=null;
        URL url = null;
        try {
            url = new URL(templateMsgUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != paramStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(paramStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            res=buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  res;
    }

}
